package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private ImageProperties imageProperties;
    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile file) throws IOException {
        if(ObjectUtils.isEmpty(file) || file.isEmpty() ) {
            return ResultVO.failed("文件不能为空");
        }

        if( !imageProperties.getTypes().contains(file.getContentType()) ) {
            String types = imageProperties.getTypes().stream()
                    .map( (type) -> type.substring(type.lastIndexOf("/") + 1))
                    .collect(Collectors.joining("."));

            return ResultVO.failed("只支持" + types + "类型的图片!");
        }

        String fileName = IdUtil.simpleUUID() + "." + FileNameUtil.getSuffix(file.getOriginalFilename());

        File upload = new File(imageProperties.getUploadDir());
        if(!upload.exists()) {
            upload.mkdirs();
        }

        File destFile = new File(upload, fileName);

        file.transferTo(destFile);

        String path = imageProperties.getMapping().endsWith("/") ?
                imageProperties.getMapping() + fileName : imageProperties.getMapping() + "/" + fileName;
        return ResultVO.success(path);
    }

}
